﻿using SIR.Common;
using SIR.Common.Condition;
using SIR.Entities.Interfaces;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace SIR.Entities.Implementations
{
	/// <summary>
	/// A user within the system including the profile, library, and favorite images
	/// </summary>
	public class User : Entity, IUser
	{
		private ILibrary _library;
		private IReadOnlyCollection<IFavoriteImage> _favoriteImages;
		/// <summary>
		/// Gets the user's library
		/// </summary>
		[Common.DatabaseAccess(DatabaseAccessRights.None)]
		public ILibrary Library
		{
			get
			{
				if (_library == null)
				{
					_library = DAL.DataServer.Find<Library>(new Predicate("UserId", Id, PredicateOperator.EqualTo)).Results.FirstOrDefault();
				}

				return _library;
			}
		}
		/// <summary>
		/// Gets or sets the nickname for the user
		/// </summary>
		[Common.DatabaseAccess(DatabaseAccessRights.ReadWrite)]
		public string Nickname { get; set; }
		/// <summary>
		/// Gets or sets the email for the user
		/// </summary>
		[Common.DatabaseAccess(DatabaseAccessRights.ReadWrite)]
		public string Email { get; set; }
		/// <summary>
		/// Gets or sets the passowrd for the user
		/// </summary>
		[Newtonsoft.Json.JsonIgnore]
		[Common.DatabaseAccess(DatabaseAccessRights.ReadWrite)]
		public string Password { get; set; }
		/// <summary>
		/// Gets or sets the number of invalid authentication attempts for the user
		/// </summary>
		[Newtonsoft.Json.JsonIgnore]
		[Common.DatabaseAccess(DatabaseAccessRights.ReadWrite)]
		public int InvalidAttempts { get; set; }
		/// <summary>
		/// Gets the list of favorite images for the user
		/// </summary>
		[Common.DatabaseAccess(DatabaseAccessRights.None)]
		public IReadOnlyCollection<IFavoriteImage> FavoriteImages
		{
			get
			{
				if (_favoriteImages == null)
				{
					_favoriteImages = new ReadOnlyCollection<FavoriteImage>(DAL.DataServer.Find<FavoriteImage>(
						new Predicate("UserId", Id, PredicateOperator.EqualTo)).Results);
				}
				return _favoriteImages;
			}
		}

		IReadOnlyCollection<long> _favoriteImageIds;
		/// <summary>
		/// Gets the image Ids from the list of favorite images
		/// </summary>
		[Common.DatabaseAccess(DatabaseAccessRights.None)]
		public IReadOnlyCollection<long> FavoriteImageIds
		{
			get
			{
				if (_favoriteImageIds == null)
				{
					_favoriteImageIds = new ReadOnlyCollection<long>(FavoriteImages.Select(img => img.ImageId).ToList());
				}
				return _favoriteImageIds;
			}
		}
	}
}

